package cn.wp.common.core.authentication;

import cn.wp.common.core.WpVar;
import cn.wp.common.core.authentication.cache.AuthenticationCache;
import cn.wp.common.core.authentication.cache.LocalCache;
import cn.wp.common.core.web.WpWebContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 身份认证上下文
 * Created by chenyb on 2019/09/27
 */
@Component
public class AuthenticationContext {

    private static AuthenticationContext INSTANCE;

    public AuthenticationContext(){
        INSTANCE = this;
    }

    public static AuthenticationContext self(){
        return INSTANCE;
    }

    @Autowired
    private AuthenticationCache authenticationCache;

    public void add(Token token,AuthenticationInfo authenticationInfo){
        authenticationCache.set(token.getTokenId(),authenticationInfo);
    }

    public AuthenticationInfo currentUser(){
        return authenticationCache.get(getKey());
    }

    public void remove(){
        authenticationCache.remove(getKey());
    }

    public void refresh(AuthenticationInfo authenticationInfo){
        authenticationCache.refresh(getKey(),authenticationInfo);
    }

    private String getKey(){
        String key = (String)WpWebContext.getRequest().getAttribute(WpVar.TOKEN_ID_KEY);
        return key;
    }
}
